package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;


import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class SimpleRedisLock implements ILock {

    private StringRedisTemplate redisTemplate;

    private String lockName;

    private final String LOCK_PREFIX = "lock:";

    private final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String lockName) {
        this.redisTemplate = redisTemplate;
        this.lockName = lockName;
    }

    @Override
    public boolean trylock(long timeoutSec) {
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean success = redisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + lockName, threadId
                , timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    //基于lua脚本保证判断线程标识一致和释放锁的原子性
    @Override
    public void unlock() {
        //调用lua脚本
        redisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(LOCK_PREFIX + lockName),
                ID_PREFIX + Thread.currentThread().getId()
                );

    }
    //无法保证判断线程标识一致和释放锁的原子性
    /*@Override
    public void unlock() {
        String currentId = redisTemplate.opsForValue().get(LOCK_PREFIX + lockName);
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        if (threadId.equals(currentId)) {
            redisTemplate.delete(LOCK_PREFIX + lockName);
        }
    }*/
}
